<!--
* description: 备件销售退款
* author: xiaochengzuan
* createdDate: 2021-2-24
-->

<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />

  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/pa/salesManagementOfSparePartsInOutlets'
import Vue from 'vue'

export default {
  name: 'SalesOfSpareParts',

  components: {
    OneTableTemplate

    // Detail: () =>import('./detail')
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // this.$refs['multipleTable'].data = [{bigAreaCode:'1'}]
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      refundData: [],
      editPopupsVisibleDetail: false,
      editRowData: {},
      editRowDataDetail: {},
      // 网格查询API配置对象
      apiConfig: orgApis.salesOfSparePartsquery,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'cancel',
          clickEvent: this.refund,
          text: '退款',
          position: 'right'
        },

        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },

        {
          compKey: 'btnKey4',
          size: 'small',
          //   clickEvent: () => this.batchDelete(),
          // clickEvent: this.add,
          text: '打印',
          name: '',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [

            {
              compKey: 'compKey5',
              labelName: '客户性质：',
              codeField: 'customerType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '0', statusText: '一般客户' },
                { statusId: '2', statusText: '授权店' },
                { statusId: '1', statusText: '直营店' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey1',
              labelName: '销售单号：',
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '客户名称：',
              codeField: 'customerName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },

            {
              compKey: 'compKey3',
              labelName: '销售类型：',
              codeField: 'saleType',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [
                { statusId: '0', statusText: '商城订单' },
                { statusId: '1', statusText: '呆滞件销售' },
                { statusId: '2', statusText: '常规销售' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },

            {
              compKey: 'compKey4',
              labelName: '收款状态：',
              codeField: 'settlementStatus',
              component: () => import('@/components/org/LookupValue'),
              oFields: 'statusId,statusText',
              options: [

                { statusId: '0', statusText: '未结算' },
                { statusId: '1', statusText: '已结算' },
                { statusId: '2', statusText: '已结清' }
              ],
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },

            {
              compKey: 'compKey6',
              labelName: '制单人：',
              codeField: 'dlrMakerId',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '制单日期：',
              codeField: 'startDate,endDate',
              component: () => import('@/components/org/datePicker/andtDatePicker'),
              type: 'YYYY-MM-DD',
              format: 'yyyy-MM-dd',
              dateOptionsType: '0',
              isMul: false,
              isMust: false
            }

            //   {
            //   compKey: 'compKey4',
            //   labelName: '所属期间：',
            //   codeField: 'bigAreaName3',
            //   component: () => import('@/components/org/datePicker/andtDatePicker'),
            //   type: 'andtDatePicker',
            //   isMul: false,
            //   isMust: true
            // },

          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'releaseId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'saleOrderCode',
              label: '销售单号',
              hidden: false,
              width: 140
            },
            {
              prop: 'customerTypeName',
              label: '客户性质',
              hidden: false
            },
            {
              prop: 'saleTypeName',
              label: '销售类型'
            },
            {
              prop: 'customerName',
              label: '客户名称'
            },
            {
              prop: 'customerPhone',
              label: '联系电话',
              width: 140
            },
            {
              prop: 'partNo',
              label: '备件编号',
              width: 140
            },
            {
              prop: 'partName',
              label: '备件名称'
            },
            {
              prop: 'salePrice',
              label: '销售价格'
            },
            {
              prop: 'saleQty',
              label: '销售数量'
            },
            {
              prop: 'saleAmount',
              label: '销售金额'
            },
            {
              prop: 'outboundQty',
              label: '已出库数量'
            },
            {
              prop: 'returnQty',
              label: '退货数量'
            },
            {
              prop: 'refundAmount',
              label: '退款金额'
            },
            {
              prop: 'actualAmount',
              label: '退款金额1',
              hidden: true
            }

          ],

      // 网格勾选
      callbackObj: {
        // 手动勾选时
        onCheckSelect: (selection, row) => {
          // alert('123')
          // console.log(selection)
          // console.log(row)
          this.refundData = selection
        },
        onCheckSelectChange: (selection) => {
          this.refundData = selection
          // alert('123')
          // this.onCheckSelectChange1(selection);
        }
      },

      // 表单查询数据
      formField: this.$utils.getFormField(this, {

        customerType: '',
        saleOrderCode: '',
        customerName: '',
        saleType: '',
        settlementStatus: '',
        dlrMakerId: '',
        startDate: '',
        endDate: '',

        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode])
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
    this.$refs.multipleTable.list = [
      { 'releaseId': '1' }
    ]
  },

  methods: {
    // 编辑获取数据
    edit(index) {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
    },
    // 退款
    refund() {
      if (this.refundData.length <= 0) return this.$message.warning('请勾选至少一条数据！')

      const that = this

      let refundObj = {}
      refundObj = {
        refundObj: that.refundData
      }
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: orgApis.salesOfSparePartsrefund,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: refundObj

      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: response.msg /* 收款成功*/,
            type: 'success',
            duration: 1000
          })
          this.queryTable(1)
        } else {
          // 保存失败
          this.$message({
            message:
            response.msg,
            type: 'warn',
            uration: 1000
          })
        }
        // this.curPopupsVisible = false
      })
    },

    // 导出
    export() {
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      month = (month < 10 ? '0' + month : month)
      day = (day < 10 ? '0' + day : day)
      var mydate = year.toString() + month.toString() + day.toString()
      const returnObj = {
        // api配置
        apiConfig: {
          APIUrl: '/mp/e3sh/basics/ve/CarTypeService/exportCarType.do'
        },
        variables: this.formField
      }
      returnObj.variables.dataType = 'excel'
      const paramD = this.$getParams(returnObj)
      this.$requestAPI(paramD).then(res => {
        this.$utils.downloadFile(res, `车系维护${mydate}.xlsx`)
      })
    }
  }
}
</script>
